//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Windows;
using System.Windows.Input;
using OpenLS.Core;
using OpenLS.UI;

namespace OpenLS.Spreadsheet.UI
{
    class GridPageSetup
    {
        internal static void EnableCommands (UIElement grid)
        {
            grid.CommandBindings.Add(new CommandBinding(ViewCommands.SetPageMargin, onSetPageMargin, onHasWorksheet));
            grid.CommandBindings.Add(new CommandBinding(ViewCommands.SetPaperSize, onSetPaperSize, onHasWorksheet));
            grid.CommandBindings.Add(new CommandBinding(ViewCommands.SetOrientation, onSetOrientation, onHasWorksheet));
            grid.CommandBindings.Add(new CommandBinding(SpreadsheetCommands.SetPrintArea, onSetPrintArea, onHasWorksheet));
            grid.CommandBindings.Add(new CommandBinding(SpreadsheetCommands.ClearPrintArea, onClearPrintArea, onHasWorksheet));

        }

        private static void onClearPrintArea(object sender, ExecutedRoutedEventArgs e)
        {
            Worksheet worksheet = getWorksheet(sender);
            worksheet.Workbook.RemoveDefinedName(BuiltInDefinedNames.PrintArea);
        }

        private static void onSetPrintArea(object sender, ExecutedRoutedEventArgs e)
        {
            Worksheet worksheet = getWorksheet(sender);
            worksheet.Workbook.RemoveDefinedName(BuiltInDefinedNames.PrintArea);
            worksheet.Workbook.DefineName(BuiltInDefinedNames.PrintArea, worksheet.Selection.FullLabel);
        }

        private static void onSetOrientation(object sender, ExecutedRoutedEventArgs e)
        {
            Worksheet ws = getWorksheet(sender);
            ws.PageSetup.Orientation = (Orientation)e.Parameter;
            e.Handled = true;
        }

        static void onSetPageMargin(object sender, ExecutedRoutedEventArgs e)
        {
            Worksheet ws = getWorksheet(sender);
            ws.PageMargins = (PageMargins) e.Parameter;
            e.Handled = true;
            
        }
        private static void onSetPaperSize(object sender, ExecutedRoutedEventArgs e)
        {
            Worksheet ws = getWorksheet(sender);
            ws.PageSetup.PaperSize = (PaperSize) e.Parameter;
            e.Handled = true;
        }

        private static void onHasWorksheet(object sender, CanExecuteRoutedEventArgs args)
        {
            args.CanExecute = getWorksheet(sender) != null;
            args.Handled = true;
        }

        private static Worksheet getWorksheet(object sender)
        {
            return SpreadsheetElement.GetWorksheet(sender);
        }
    }
}